class Api::AuthenticationController < ApplicationController
  skip_before_action :authenticate_request  # 如果其他接口需要认证

  def login
    user = User.find_by(username: params[:username])

    if user&.authenticate(params[:password])
      token = jwt_encode(user_id: user.id)
      render json: {
        token: token,
        user: { id: user.id, username: user.username }
      }, status: :ok
    else
      render json: { error: "用户名或密码错误" }, status: :unauthorized
    end
  end

  private

  # JWT 编码（建议设置过期时间）
  def jwt_encode(payload, exp = 24.hours.from_now)
    payload[:exp] = exp.to_i
    JWT.encode(payload, Rails.application.credentials.secret_key_base)
  end

end
